package io.github.heollhai.common.config.security;

import io.github.heollhai.common.basic.BasicKey;
import io.github.heollhai.common.entity.bo.RoleBo;
import io.github.heollhai.common.entity.security.dto.UserByRoleDto;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.List;
import java.util.function.Supplier;

/**
 * @Author: lmf
 * @Create: 2024/8/5 17:11
 * Description: 验证用户是否有对应的权限可以访问接口
 */
@Component
@Slf4j
public class RbacManager implements AuthorizationManager<RequestAuthorizationContext> {
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public AuthorizationDecision check(Supplier<Authentication> authentication,
                                       RequestAuthorizationContext requestAuthorizationContext) {
        HttpServletRequest request = requestAuthorizationContext.getRequest();
        Authentication authentication1 = authentication.get();
        if (authentication1.getPrincipal() instanceof UserByRoleDto userByRoleDto) {
            List<String> roleNames = userByRoleDto.getUserBo().getRoleList().stream().map(RoleBo::getName).toList();
            // 超级管理员直接开放权限
            if(roleNames.contains(BasicKey.SUPER_ADMIN)){
                return new AuthorizationDecision(true);
            }

            if (userByRoleDto.getBackAuthUrls().isEmpty()) {
                return new AuthorizationDecision(false);
            }
            for (String backAuthUrl : userByRoleDto.getBackAuthUrls()) {
                // 判断当前请求的url是否在权限列表中
                String requestURI = request.getRequestURI();
                System.out.println(requestURI);
                if (antPathMatcher.match(backAuthUrl, request.getRequestURI())) {
                    return new AuthorizationDecision(true);
                }

            }
            return new AuthorizationDecision(false);
        }
        return new AuthorizationDecision(false);
    }


}
